package com.study.postprocessor;

import com.study.utils.BaseClassScanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;

import java.util.Map;

//Step3：定义bean工厂后处理类，实现BeanDefinitionRegistryPostProcessor（即BeanFactoryPostProcessor子接口）接口，从而实现Bean的动态注入
public class MyBeanFactoryPostProcessor3 implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        //指定要被扫描到的包路径
        String basePackage = "com.study";
        //扫描basePackage及其子包下被@MyComponent修饰的类
        Map<String, Class> myComponentClassMap = BaseClassScanUtils.scanMyComponentAnnotation(basePackage);
        //遍历Map集合，创建BeanDefinition对象进行注册
        myComponentClassMap.forEach((beanName,clazz) -> {
            BeanDefinition beanDefinition = new RootBeanDefinition();
            beanDefinition.setBeanClassName(clazz.getName());
            beanDefinitionRegistry.registerBeanDefinition(beanName,beanDefinition);
        });
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

    }
}
